﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using Visifire.Charts;
using Visifire.Commons;
using Negocio;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Data;
using Microsoft.Windows.Controls;
using Microsoft.Windows.Controls.Primitives;
using Microsoft.Win32;
using System.Printing;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
/*using System.Drawing.Printing;
using System.Drawing;*/



namespace Presentacion
{
    public partial class WIndiviudalReport
    {
        private DataTable table;
        private RenderAs chartType;
        private Title chartTitle;
        private Chart visiChart;        
        
        public WIndiviudalReport()
        {
            this.InitializeComponent();
            dpEven.SelectedDate = DateTime.Today;
            dpSince.SelectedDate = DateTime.Today;
            table = new DataTable();
            cbxPlayer.ItemsSource = Club.getInstance().Players;
            cbxEvaluation.ItemsSource = Club.getInstance().Evaluations;
            dpEven.SelectedDate = DateTime.Today;
            dpSince.SelectedDate = DateTime.Today;
            loadCbxChartTypes();
            chartTitle = new Title();
            visiChart = new Chart();            
            chartType = RenderAs.Column;            
        }

        private void cbxEvaluation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxPlayer.SelectedIndex != -1)
            {                
                ObservableCollection<PlayerExecution> execList = Club.getInstance().evaluationsOfPlayerByDates(Club.getInstance().Players[cbxPlayer.SelectedIndex], Club.getInstance().Evaluations[cbxEvaluation.SelectedIndex], dpSince.SelectedDate.Value, dpEven.SelectedDate.Value);
                loadTable(execList);
            }
        }

        public void loadChart(DataSeries ds)
        {
            visiChart.Titles.Clear();
            visiChart.Titles.Add(chartTitle);
            ds.RenderAs = chartType;
            visiChart.Width = gridChart.Width; 
            visiChart.Height = gridChart.Height;
            visiChart.Series.Add(ds);
            gridChart.Children.Clear(); 
            gridChart.Children.Add(visiChart);
        }

        private void cbxPlayer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxEvaluation.SelectedIndex != -1 && cbxPlayer.SelectedIndex != -1)
            {
                chartTitle.Text = ((Player)(cbxPlayer.SelectedItem)).CompleteName;
                ObservableCollection<PlayerExecution> execList = Club.getInstance().evaluationsOfPlayerByDates(Club.getInstance().Players[cbxPlayer.SelectedIndex], Club.getInstance().Evaluations[cbxEvaluation.SelectedIndex], dpSince.SelectedDate.Value, dpEven.SelectedDate.Value);
                loadTable(execList);

            }
        }

        private void loadTable(ObservableCollection<PlayerExecution> execList)
        {
            table.Clear();
            table.Columns.Clear();
            dataGrid1.Columns.Clear();
            dataGrid1.ItemsSource = null;
            IEnumerator<PlayerExecution> plyexec = execList.GetEnumerator();
            DataColumn colGraf = new DataColumn("Graficar", typeof(bool));
            table.Columns.Add(colGraf);
            DataColumn colJug = new DataColumn("Fecha", typeof(string));
            colJug.ReadOnly = true;
            table.Columns.Add(colJug);
            while (plyexec.MoveNext())
            {
                IEnumerator<TestValue> p = plyexec.Current.Values.GetEnumerator();
                while (p.MoveNext())
                {
                    DataColumn colTest = new DataColumn(p.Current.Test.Name, typeof(float));
                    colTest.ReadOnly = true;
                    if (!table.Columns.Contains(colTest.ColumnName))   
                    {
                        table.Columns.Add(colTest);
                    }                    
                }    
                p.Reset();
                DataRow row = table.NewRow();
                while (p.MoveNext())
                {
                    row["Fecha"] = plyexec.Current.Date.ToShortDateString();
                    row[p.Current.Test.Name] = p.Current.ValueExecution;
                    row["Graficar"] = false;
                }
                table.Rows.Add(row);
                p.Reset();
            }
            dataGrid1.FrozenColumnCount = 2;
            dataGrid1.ItemsSource = table.DefaultView;
        }

        private void dpSince_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxEvaluation.SelectedIndex != -1 && cbxPlayer.SelectedIndex != -1)
            {
                ObservableCollection<PlayerExecution> execList = Club.getInstance().evaluationsOfPlayerByDates(Club.getInstance().Players[cbxPlayer.SelectedIndex], Club.getInstance().Evaluations[cbxEvaluation.SelectedIndex], dpSince.SelectedDate.Value, dpEven.SelectedDate.Value);
                loadTable(execList);
            }
        }

        private void dpEven_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxEvaluation.SelectedIndex != -1 && cbxPlayer.SelectedIndex != -1)
            {
                ObservableCollection<PlayerExecution> execList = Club.getInstance().evaluationsOfPlayerByDates(Club.getInstance().Players[cbxPlayer.SelectedIndex], Club.getInstance().Evaluations[cbxEvaluation.SelectedIndex], dpSince.SelectedDate.Value, dpEven.SelectedDate.Value);
                loadTable(execList);
            }
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            visiChart = new Chart();
            for (int j = 0; j < table.Rows.Count; j++)
            {
                if (table.Rows[j]["Graficar"].ToString().Equals("True"))
                {
                    DataSeries ds = new DataSeries();
                    for (int i = 2; i < table.Columns.Count; i++)
                    {
                        DataPoint dp = new DataPoint();
                        dp.YValue = Double.Parse(table.Rows[j][table.Columns[i].ColumnName].ToString());
                        dp.AxisXLabel = table.Columns[i].ColumnName;
                        dp.XValue = null;
                        ds.DataPoints.Add(dp);
                    }
                    string dsName = table.Rows[j]["Fecha"].ToString();
                    string[] dsDate = dsName.Split('/');
                    ds.Name = "Fecha"+dsDate[0] + dsDate[1] + dsDate[2];
                    loadChart(ds);
                }
            }            
        }

        private void dataGrid1_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;            
            while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
            if (dep == null)
                return;

            if (dep is DataGridColumnHeader)
            {
                visiChart = new Chart();
                DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
                DataSeries ds = new DataSeries();
                chartTitle.Text = columnHeader.Column.Header.ToString();
                if (!(columnHeader.Column.Header.Equals("Fecha") || columnHeader.Column.Header.Equals("Graficar")))
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        DataPoint dp = new DataPoint();
                        dp.YValue = Double.Parse(table.Rows[i][columnHeader.Column.Header.ToString()].ToString());
                        dp.AxisXLabel = table.Rows[i]["Fecha"].ToString();
                        dp.XValue = null;
                        ds.DataPoints.Add(dp);
                    }
                    loadChart(ds);
                }
            }
            if (dep is DataGridCell)
            {
                DataGridCell cell = dep as DataGridCell;
            }
        }

        private void gridChart_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;
            while ((dep != null) && !(dep is Chart))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
            if (dep is Chart)
            {
                Chart cell = new Chart();
                cell = dep as Chart;
                visiChart = new Chart();
                string[] toolTip = cell.ToolTips[0].Text.Split(',');
                string xValue = toolTip[0];
                for (int j = 0; j < cell.Series.Count; j++)
                {
                    DataSeries ds = new DataSeries();
                    for (int i = 0; i < cell.Series[j].DataPoints.Count; i++)
                    {
                        if (!(cell.Series[j].DataPoints[i].AxisXLabel.Equals(xValue)))
                        {
                            DataPoint dp = new DataPoint();
                            dp.YValue = cell.Series[j].DataPoints[i].YValue;
                            dp.XValue = null;
                            dp.AxisXLabel = cell.Series[j].DataPoints[i].AxisXLabel;
                            ds.DataPoints.Add(dp);
                        }
                    }
                    string dsName = table.Rows[j]["Fecha"].ToString();
                    string[] dsDate = dsName.Split('/');
                    ds.Name = "Fecha" + dsDate[0] + dsDate[1] + dsDate[2];
                    loadChart(ds);
                }
            }
        }

        private void cbxChartType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxChartType.SelectedIndex != -1)
            {
                chartType = (RenderAs)cbxChartType.SelectedItem;
                dataGrid1_SelectionChanged(sender, e);
                cbxChartType.SelectedIndex = -1;
            }
        }

        private void loadCbxChartTypes()
        {
            IList<RenderAs> chartTypes = new List<RenderAs>();
            chartTypes.Add(RenderAs.Area);
            chartTypes.Add(RenderAs.Bar);
            chartTypes.Add(RenderAs.Bubble);
            chartTypes.Add(RenderAs.Column);
            chartTypes.Add(RenderAs.Doughnut);
            chartTypes.Add(RenderAs.Line);
            chartTypes.Add(RenderAs.Pie);
            chartTypes.Add(RenderAs.Point);
            chartTypes.Add(RenderAs.StackedArea);
            chartTypes.Add(RenderAs.StackedArea100);
            chartTypes.Add(RenderAs.StackedBar);
            chartTypes.Add(RenderAs.StackedBar100);
            chartTypes.Add(RenderAs.StackedColumn);
            chartTypes.Add(RenderAs.StackedColumn100);
            cbxChartType.ItemsSource = chartTypes;
            cbxChartType.SelectedIndex = 3;
        }

        private void dataGrid1_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //visiChart = new Chart();
            //chartTitle.Text = ((Player)cbxPlayer.SelectedItem).CompleteName;            
            //for (int j = 0; j < table.Rows.Count; j++)
            //{
            //    if (table.Rows[j]["Graficar"].ToString().Equals("True"))
            //    {
            //        DataSeries ds = new DataSeries();
            //        for (int i = 2; i < table.Columns.Count; i++)
            //        {
            //            DataPoint dp = new DataPoint();
            //            dp.YValue = Double.Parse(table.Rows[j][table.Columns[i].ColumnName].ToString());
            //            dp.AxisXLabel = table.Columns[i].ColumnName;
            //            dp.XValue = null;
            //            ds.DataPoints.Add(dp);
            //        }
            //        string dsName = table.Rows[j]["Fecha"].ToString();
            //        string[] dsDate = dsName.Split('/');
            //        dsName = "";
            //        for (int i = 0; i < dsDate.Length; i++)
            //        {
            //            dsName = dsName + dsDate[i];
            //        }                    
            //        loadChart(ds);
            //    }
            //}            
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            Nullable < Boolean > print = printDialog.ShowDialog();
            if (print == true)
            {
                this.btnExport.Visibility = Visibility.Collapsed;
                this.btnPrint.Visibility = Visibility.Collapsed;
                this.cbxChartType.Visibility = Visibility.Collapsed;
                printDialog.PrintVisual(LayoutRoot, "Reporte individual");
                this.btnExport.Visibility = Visibility.Visible;
                this.btnPrint.Visibility = Visibility.Visible;
                this.cbxChartType.Visibility = Visibility.Visible;
            }            
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog v = new SaveFileDialog();
            v.Filter = "Excel(*.csv)|*.csv|Todos los Archivos(*.*)|*.*";
            v.AddExtension = true;
            v.DefaultExt = ".csv";
            bool yes = v.ShowDialog().Value;
            if (yes)
            {
                try
                {
                    if (this.cbxEvaluation.SelectedIndex != -1 && this.cbxPlayer.SelectedIndex != -1)
                    {
                        string playerID = ((Player)this.cbxPlayer.SelectedItem).IdentityDocument;
                        string evaluationName = this.cbxEvaluation.Text;
                        Club.getInstance().writeOnePlayerExecutionsBetweenDates(dpSince.SelectedDate.Value, dpEven.SelectedDate.Value, playerID, evaluationName, v.FileName);
                    }                    
                }
                catch (ArgumentOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (IndexOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }





        /*private void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            String textToPrint = "Prueba impresion \n";            
            Font printFont = new Font("Courier New", 12);
            int leftMargin = e.MarginBounds.Left;
            int topMargin = e.MarginBounds.Top;            
            //e.Graphics.DrawString(textToPrint, printFont, System.Drawing.Brushes.Black, leftMargin, topMargin);
            for (int i = 0; i < table.Rows.Count; i++)
            {
                textToPrint = textToPrint + "\n";
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    textToPrint = textToPrint + "\t" + table.Rows[i][table.Columns[j].ColumnName];
                }                
            }
            e.Graphics.DrawString(textToPrint, printFont, System.Drawing.Brushes.Black, leftMargin, topMargin);
            /*e.Graphics.
            
            System.Windows.Forms.PaintEventArgs myPaintArgs = new PaintEventArgs(e.Graphics, new Rectangle(new Point(0, 0), this.Size));
            this.InvokePaint(dataGrid1, myPaintArgs);

        }*/

    }
}